package app;

import java.util.*;

import com.StarMicronics.StarIOSDK.*;
import com.StarMicronics.StarIOSDK.PrinterFunctions.*;
import com.starmicronics.stario.*;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.*;

public class Printer {
	public View view;
	private TextView textView;
	private TextView uilabel_portname;
	MyAdapter adapter;
	private ListView printers;
	private static Vector<PortInfo> printerArray = new Vector<PortInfo>();
	
	private void printTextFormating() {
		WaittingAlertView alert = WaittingAlertView.createWaittingAlertView();
		alert.setLoadingText("printing");
		alert.show();
	    Handler handler = new Handler(){
	        public void handleMessage(Message msg) {
		    	WaittingAlertView alertView = (WaittingAlertView) msg.obj;
	    		String portName = PrinterTypeActivity.getPortName();
	    		String portSettings = PrinterTypeActivity.getPortSettings();

	    		boolean underline = false;
	    		boolean emphasized = false;
	    		boolean upsidedown = false;
	    		boolean invertColor = false;
	    	    
	    		byte heightExpansion = 0;
	    		byte widthExpansion = 0;
	    	    int leftMargin = 0;
	    	    
	    	    PrinterFunctions.Alignment alignment = Alignment.Left;
	    	    byte[] texttoprint = textView.getText().toString().getBytes();

	        	MiniPrinterFunctions.PrintText(AppDelegate.sharedInstance().activity, portName, portSettings, underline, emphasized, upsidedown, invertColor, heightExpansion, widthExpansion, leftMargin, alignment, texttoprint);
	        	super.handleMessage(msg);  
	        	
	        	alertView.cancel();
	        	alertView = null;
	        }
	    };
	    Message message = handler.obtainMessage();
	    message.obj = alert;
	    handler.sendMessage(message);
	}
	
	private void selectFirst() {
		if (printerArray.size() > 0) {
			PortInfo portInfo = printerArray.elementAt(0);
			
			PrinterTypeActivity.setPortName(portInfo.getPortName());
			PrinterTypeActivity.setPortSettings("mini");
			
			uilabel_portname.setText(portInfo.getPortName());
		}
	}
	
	private void pushButtonSearch() {
		printerArray = new Vector<PortInfo>();
    	try {

    		List<PortInfo> BTPortList  = StarIOPort.searchPrinter("BT:");
    		List<PortInfo> TCPPortList = StarIOPort.searchPrinter("TCP:");
    		
	    	for (PortInfo portInfo : TCPPortList) {
	    		printerArray.add(portInfo);
	    	}

    		for (PortInfo portInfo : BTPortList) {
    			printerArray.add(portInfo);
	    	}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	printers.setVisibility(View.VISIBLE);
    	adapter.notifyDataSetInvalidated();
    	selectFirst();
    	view.setVisibility(View.VISIBLE);
    	textView.setVisibility(View.INVISIBLE);
	}
	
	private void back() {
		e_print.cancel();
	}
	
	
	public Printer(String printContent) {
		loadXml();
		textView.setText(printContent);
		if (printerArray.size() == 0) {
			Handler handler = new Handler(){  
		        public void handleMessage(Message msg) {  
		        	pushButtonSearch();
		        	super.handleMessage(msg);  
		        } 
		    };  
		    handler.sendMessage(handler.obtainMessage());
			view.setVisibility(View.INVISIBLE);
		} else {
			selectFirst();
		}
		adapter.notifyDataSetInvalidated();
	}
	
	
	
	
	
	private final class ViewHolder {  
        private TextView textLabel;
        private TextView detailTextLabel;
    }

	
	private final class MyAdapter extends BaseAdapter {  
        private LayoutInflater mInflater;
        public MyAdapter(Context context) {  
            this.mInflater = LayoutInflater.from(context);  
        }  
        public int getCount() {  
        	if (printerArray == null) {
        		return 1;
        	} else {
            	return printerArray.size() + 1;
        	}
        }
        public Object getItem(int arg0) {
        	if (printerArray == null || arg0 == printerArray.size()) {
        		return null;
        	} else {
                return printerArray.elementAt(arg0);  
        	}
        }  
        public long getItemId(int arg0) {  
            return arg0;  
        }  
        public View getView(int position, View convertView, ViewGroup parent) {  
            ViewHolder holder = null;  
            if (convertView == null) {  
                holder = new ViewHolder();  
                convertView = mInflater.inflate(R.layout.print_cell, null);  
                holder.textLabel = (TextView) convertView.findViewById(R.id.textLabel);  
                holder.detailTextLabel = (TextView) convertView.findViewById(R.id.detailTextLabel);

                convertView.setTag(holder);
            } else {  
                holder = (ViewHolder) convertView.getTag();  
            }
            
            if (position < printerArray.size()) {
                PortInfo port = printerArray.elementAt(position);
                holder.textLabel.setText(port.getModelName());
                holder.detailTextLabel.setText(port.getPortName()+"("+port.getMacAddress()+")");
            } else {
            	holder.textLabel.setText("Back");
            	holder.detailTextLabel.setText(null);
            }
            return convertView;  
        }
    }
	
	private void didSelectRowAtIndexPath(int index) {
		if (index < printerArray.size()) {
			PortInfo portInfo = printerArray.elementAt(index);
			PrinterTypeActivity.setPortName(portInfo.getPortName());
			PrinterTypeActivity.setPortSettings("mini");
			
			uilabel_portname.setText(portInfo.getPortName());
		}
		printers.setVisibility(View.INVISIBLE);
		textView.setVisibility(View.VISIBLE);
	}
	
	
	
	
	
	public E_PrintView e_print;
	private Button button_back;
	private Button button_print;
	private Button button_search;
	private void loadXml() {
        view = (View)AppDelegate.sharedInstance().activity.getLayoutInflater().inflate(R.layout.printer, null);
        button_back = (Button) view.findViewById(R.id.button_back);
        button_print = (Button) view.findViewById(R.id.button_print);
        button_search = (Button) view.findViewById(R.id.button_search);
        textView = (TextView) view.findViewById(R.id.textView);
        printers = (ListView) view.findViewById(R.id.printers);
        uilabel_portname = (TextView) view.findViewById(R.id.uilabel_portname);
		
		button_back.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				back();
			}
		});
		button_print.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				printTextFormating();
			}
		});
		button_search.setOnClickListener(new OnClickListener() {
			public void onClick(View arg0) {
				pushButtonSearch();
			}
		});
        
		adapter = new MyAdapter(AppDelegate.sharedInstance().activity);
		printers.setAdapter(adapter);
		printers.setOnItemClickListener(new AdapterView.OnItemClickListener() {  
	        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {  
	        	didSelectRowAtIndexPath(arg2);
	        }
		});

	}
}
